<template>
  <div class="sui-cart">
    <div class="my-header">
      <i class="back" @click="$router.go(-1)"></i>
      <strong>购物车</strong>
      <span class="edit" @click="triggerDel = !triggerDel"><span v-if="isLogin">{{triggerDel?'完成':'编辑'}}</span></span>
    </div>
    <!-- 购物车列表 -->
    <div class="Section">
      <div class="login-info cart-tips" v-if="!isLogin">
        <p>登录后同步电脑与手机购物车中的商品</p>
        <button class="info-btn" @click="$router.push({name:'login',query:{redirect:'/cart'}})">点击登录</button>
      </div>
      <mt-loadmore :style="{width:'100%',height: '85%',paddingTop: isLogin ? '1.2rem' : '0'}" :top-method="loadTop" :bottom-distance="distance"
        :bottom-all-loaded="allLoaded" :auto-fill="false" ref="loadmore">
        <div v-if="cartList" class="goods">
          <div v-for="store in cartList" :key="store.uId">
            <div class="store">
              <i class="iconfont" :class="[store.checked ? 'icon-select' :'icon-select-default']" @click="checkedStore(store)"></i>
              <span>{{store.supplierWarehouse}}</span>
            </div>
            <div class="store-pd" v-for="(item,index) in store.goodsList" :key="index">
              <mt-cell-swipe v-for="size in item.sizeList" :key="size.cartId" :right="[ { content: '删除',  style:swipeDel,handler: () => handleDel(size.cartId)}]">
                <div class="store-pd-item" :ref="size.cartId">
                  <i class="iconfont" :class="[size.checked ? 'icon-select' :'icon-select-default']" @click="checked(size,item.sizeList,store)"></i>
                  <div class="pd-images" @click="$router.push({name:'product/'+cartId})" :class="{'out_of_stock':size.stockNum==0}">
                    <img :src="item.goodsImg" alt="">
                  </div>
                  <div class="pd-info">
                    <div class="pd-title">
                      <p>{{item.sellingPoints}}</p>
                    </div>
                    <div class="pd-sku">
                      <p class="sku-info">尺码:{{size.sizeName}}</p>
                    </div>

                    <div class="pd-price">
                      <div class="left">
                        <span>&yen;</span>
                        <strong>{{size.discountMoney}}</strong>
                      </div>
                      <div class="right" v-if="size.stockNum>0">
                        <div class="cut" @click="editProductNum({item:size,increment:-1})"></div>
                        <input type="tel" pattern="^[1-9]\d*" v-model="size.cartNum" class="num-inp" :min="1" :max="size.stockNum" @change="editProductNum({item:size,counter:size.cartNum})">
                        <div class="add" @click="editProductNum({item:size,increment:1})"></div>
                      </div>
                    </div>
                    <div v-if="size.cartNum>size.stockNum &&size.stockNum!=0" class="pd-stock">
                      <span>剩余{{size.stockNum}}件</span>
                    </div>
                  </div>
                </div>
              </mt-cell-swipe>
            </div>
          </div>
          <div class="empty-info cart-tips" v-if="!cartList || cartList == ''">
            <i class="iconfont icon-cart"></i>
            <p>购物车是空的</p>
            <button class="info-btn" @click="$router.push('/index')">逛逛首页</button>
          </div>
          <!--<div class="empty" >
            <i class="iconfont icon-cart"></i>
            <p class="empty_txt">购物车是空的</p>
          </div>-->
        </div>
      </mt-loadmore>
    </div>
    <!-- 购物车列表 -->
    <!-- 底部价格计算 -->
    <div class="section-bar" v-if="isLogin">
      <div class="left">
        <span @click="selectedAllGoods"><i class="iconfont" :class="[selectedAll ? 'icon-select' : 'icon-select-default']"></i>全选</span>
        <strong v-if="!triggerDel">合计：&yen;{{totalFee}}</strong>
      </div>
      <div v-if="triggerDel" class="right" @click="handleDelAll">
        <strong>删除
          <span></span>
        </strong>
      </div>
      <div v-else class="right" @click="submitCart">
        <strong>去结算
          <span></span>
        </strong>
      </div>
    </div>
    <!-- 底部价格计算 -->
    <footertab> </footertab>
  </div>
</template>
<script>
  import footertab from '@/components/footer/footer'
  import {
    mapGetters
  } from 'vuex'
  import {
    Toast,
    MessageBox
  } from 'mint-ui'
  import {
    updateProCount,
    delCartPro,
    validateCartNum,
    submitCartPro
  } from '@/api/shop'
  export default {
    data() {
      return {
        userId: '',
        cartList: null,
        tempList: null,
        allLoaded: false,
        distance: 30,
        params: {
          status: 1 // 1 采购 2 分销
        },
        totalFee: 0,
        selectedCounter: 0,
        selectedAll: false,
        isLogin: false,
        swipeDel: {
          background: '#FF0000',
          color: '#fff'
        },
        triggerDel: false
      }
    },
    components: {
      footertab
    },
    computed: {
      ...mapGetters({
        userInfo: 'userInfo'
      }),
      proIds() {
        let proIds = ''
        this.cartList.forEach(store => {
          store.goodsList.forEach(item => {
            item.sizeList.forEach(product => {
              if (product.checked) {
                proIds = proIds + product.cartId + ','
              }
            })
          })
        })
        proIds = proIds.substring(0, proIds.length - 1)
        return proIds
      }
    },
    methods: {
      submitCart() { // 结算购物车
        const params = {
          userId: this.userInfo.id,
          cartId: this.proIds
        }
        if (this.proIds.length <= 0) {
          return Toast({
            message: '请选择商品',
            position: 'bottom',
            duration: 1000
          })
        }
        // 验证购物车数量
        validateCartNum(params).then(res => {
          const proIdsParams = {
            cartId: this.proIds
          }
          // 提交购物车
          submitCartPro(proIdsParams).then(respose => {
            const key = respose.data.key
            // this.$router.replace('createOrder/' + key)
            this.$router.replace({
              name: 'createOrder',
              query: {
                id: key
              }
            })
          }).catch(error => {
            return Toast({
              message: error.info,
              position: 'bottom'
            })
          })
        }).catch(err => {
          if (err.status === 60100) {
            MessageBox.alert('结算商品存在库存不足或暂时缺货').then(action => {
              const cartid = err.data.cartList[0].cartId
              // 滚动到指定位置
              this.$refs[cartid][0].scrollIntoView()
              // console.log(this.$refs[cartid][0].getBoundingClientRect().top)
              // console.log(this.$refs[cartid].getBoundingClientRect())
            })
          } else {
            console.log(err)
          }
        })

        // this.$store.dispatch('ConfirmSelectProduct', {
        //   SelectedList: JSON.stringify(SelectedList)
        // }).then(response => {
        //   this.$router.push('/createOrder')
        // })
      },

      handleDelAll() {
        let proIds = ''
        this.cartList.forEach(store => {
          store.goodsList.forEach(item => {
            item.sizeList.forEach(product => {
              if (product.checked) {
                proIds = proIds + product.cartId + ','
              }
            })
          })
        })
        proIds = proIds.substring(0, proIds.length - 1)
        if (proIds.length <= 0) {
          return Toast({
            message: '请选择商品',
            position: 'bottom'
          })
        }
        // 删除操作
        this.handleDel(proIds)
      },
      handleDel(id) { // 左滑商品删除
        MessageBox.confirm('确定要删除吗?').then(action => {
          if (action === 'confirm') {
            const params = {
              cartId: id
            }
            delCartPro(params).then(res => {
              this.fetchData()
            }).catch(err => {
              Toast({
                message: err.info,
                position: 'bottom',
                duration: 1000
              })
            })
          }
        }).catch(() => {})
      },
      editProductNum({
        item,
        increment,
        counter
      }) {
        // 请求接口修改购物车数量参数
        const params = {
          userId: this.userInfo.id,
          status: this.params.status,
          goodsDetailsId: encodeURI(item.goodsDetailsId),
          sizeId: item.sizeId,
          cartNum: item.cartNum,
          uId: item.uId
        }
        const count = Number(counter)
        // 如果手动输入
        if (count === 0) {
          item.cartNum = 1
          params.cartNum = 1
        } else if (!isNaN(count) && count > item.stockNum) {
          Toast({
            message: '最多只能添加' + item.stockNum + '件商品',
            position: 'bottom',
            duration: 1000
          })
          item.cartNum = item.stockNum
          params.cartNum = item.stockNum
        }
        // 如果加减
        if (isNaN(count)) {
          if (params.cartNum <= 1 && Number(increment) < 0) {
            Toast({
              message: '不能再少了',
              position: 'bottom',
              duration: 1000
            })
            return false
          } else if (params.cartNum >= item.stockNum && Number(increment) > 0) {
            Toast({
              message: '不能再多了',
              position: 'bottom',
              duration: 1000
            })
            return false
          } else if (item.cartNum > item.stockNum && Number(increment) < 0) {
            // 购物车数量大于库存是直接减到库存
            params.cartNum = item.stockNum
          } else {
            params.cartNum = Number(params.cartNum) + Number(increment)
          }
        }
        // 更新购物车数量
        updateProCount(params).then(res => {
          item.cartNum = params.cartNum
        }).catch(err => {
          Toast({
            message: err.info,
            position: 'bottom',
            duration: 1000
          })
        })
        // this.$store.dispatch('SelectProduct', params)
      },
      checkedStore(store) { // 选择店铺
        store.checked = !store.checked
        // 全选仓库下的所有商品
        store.goodsList.forEach(item => {
          item.sizeList.forEach(product => {
            product.checked = store.checked
          })
        })
        let count = 0
        // 当仓库全选的总个数等于所有仓库个数是全选
        this.cartList.forEach(item => {
          if (item.checked) return count++
        })
        if (count === this.cartList.length) {
          return this.selectedAllGoods()
        } else {
          this.selectedAll = false
        }
        this.computedTotalFee()
      },
      checked(size, item, store) { // 选择商品
        size.checked = !size.checked
        let count = 0
        // 当商品个数等于总的仓库总的商品数时候全选仓库
        item.forEach(item => {
          if (item.checked) return count++
        })

        if (count === item.length) {
          return this.checkedStore(store)
        } else {
          store.checked = false
          this.selectedAll = false
        }
        this.computedTotalFee()
      },
      selectedAllGoods() { // 选择所有
        this.cartList.forEach(store => {
          store.checked = !this.selectedAll
          store.goodsList.forEach(item => {
            item.sizeList.forEach(product => {
              product.checked = !this.selectedAll
            })
          })
        })
        this.selectedAll = !this.selectedAll
        this.computedTotalFee()
      },
      computedTotalFee() { // 合计费用
        let computedFee = 0
        // let selectedCounter = 0
        this.cartList.forEach(store => {
          store.goodsList.forEach(item => {
            item.sizeList.forEach(product => {
              if (product.checked) {
                computedFee += product.cartNum * parseFloat(product.discountMoney)
                // selectedCounter++
              }
            })
          })
        })
        // this.selectedCounter = selectedCounter
        this.totalFee = computedFee.toFixed(2)
      },
      loadTop() {
        // 下拉刷新
        this.$refs.loadmore.onTopLoaded()
        this.fetchData()
      },
      fetchData() {
        // 判断是否登录
        this.isLogin = this.userInfo ? 1 : 0
        if (!this.userInfo) return
        // 获取购物车信息
        const formData = {
          userId: this.userInfo.id,
          status: this.params.status
        }
        this.$store.dispatch('getCartProductList', formData).then(res => {
          this.cartList = res.data.cartList
          this.cartList.forEach(cart => {
            this.$set(cart, 'checked', false)
            cart.goodsList.forEach(good => {
              good.sizeList.forEach(size => {
                // 购物车数量大于库存时候
                if (size.cartNum > size.stockNum && size.stockNum !== 0) {
                  this.$set(size, 'status', 0)
                } else {
                  this.$set(size, 'status', 1)
                }
                this.$set(size, 'checked', false)
              })
            })
          })
          //  this.tempList = res.data.cartList
        }).catch(err => {
          console.log(err)
        })
      }
    },
    // mounted() {
    //   this.init()
    // },
    created() {
      this.fetchData()
    }
  }

</script>
<style lang="scss" scoped>
  @import '~assets/common/css/mixin.scss';
  .sui-cart {
    padding-bottom: 3rem;
    min-height: 100vh;
  }

  .my-header {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    z-index: 1000;
    height: 1.25rem;
    background: #fff;
    padding: $padding;
    @include flexbox(space-between, center, row, nowrap);
    border-bottom: 1px solid #eee;
    .back {
      display: block;
      width: .65rem;
      height: .65rem;
      background: url('~assets/common/images/arrow-left.png') no-repeat;
      background-size: 100%;
    }
    strong {
      font-size: 18px;
      font-weight: normal;
      color: #333;
    }
    .bheedit {
      font-size: 12px;
    }
  }

  .cart-title {
    @include flexbox(center,
    center,
    row,
    nowrap);
    font-size: 16px;
  }
  /* 购物车列表 */

  .Section {
    .cart-tips {
      margin-top: 40px;
      position: relative;
      z-index: 1;
      padding: $padding 25px;
      @include flexbox(flex-start,
      center,
      column,
      nowrap);
      i {
        color: #999;
        font-size: 60px;
      }
      .info-btn {
        border: 1px solid $red;
        color: $red;
        background: transparent;
        width: 80px;
        height: 25px;
        border-radius: 2px;
      }
      p {
        font-size: 14px;
        color: #999;
        line-height: 2;
      }
    }
    .goods {
      @include flexbox(flex-start,
      space-between,
      column,
      wrap); // padding-bottom: 3rem;
      .store {
        @include flexbox(flex-start,
        center,
        row,
        nowrap);
        background: #F5F9FC;
        flex: initial;
        font-size: 14px;
        padding: 10px;
        span {
          margin-left: 10px;
        }
      }
      .store-pd {
        @include flexbox(flex-start,
        space-between,
        column,
        wrap);
        background: #fff;
        flex: initial;
        .store-pd-item {
          @include flexbox(flex-start,
          center,
          row,
          nowrap);
          padding: 10px 0; // border-bottom: 1px solid #eee;
          &:last-child {
            border-bottom: none;
          }
          .pd-images {
            border: 1px solid #eee;
            margin: 0 10px 0 10px;
            width: 75px;
            height: 75px;
            text-align: center;
            position: relative;
            img {
              width: auto;
              height: 100%;
            }
            &.out_of_stock:after {
              content: '暂时无货';
              position: absolute;
              bottom: 0;
              left: 0;
              font-size: 13px;
              color: #fff;
              background: rgba(0, 0, 0, .7);
              width: 100%;
              height: 20px;
              line-height: 20px;
            }
          }
          .pd-info {
            @include flexbox(flex-start,
            space-between,
            column,
            wrap); // width: 100%;
            // flex: initial;
            .pd-title {
              @include textoverflow(2); // width: 90%;
              font-size: 13px;
              color: #333;
            }
            .pd-sku {
              @include textoverflow(1);
              line-height: 1.5;
              font-size: 12px;
              color: #999;
            }
            .pd-price {
              margin-top: 5px;
              @include flexbox(space-between,
              center,
              row,
              nowrap);
              flex: initial;
              .left {
                color: #e93b3d;
                span {
                  font-size: 12px;
                }
                strong {
                  font-size: 16px;
                  font-weight: normal;
                }
              }
              .right {
                @include flexbox(space-between,
                center,
                row,
                nowrap);
                flex: initial;
                border-radius: 2px;
                border: 1px solid #eee;
                width: 2.5rem;
                .cut {
                  padding: 2px 0;
                  font-size: 14px;
                  text-align: center;
                  width: 30%;
                  height: .6rem;
                  position: relative;
                  cursor: pointer;
                  &:before {
                    content: '';
                    position: absolute;
                    right: 0;
                    top: 0;
                    background: #eee;
                    width: 1px;
                    height: 100%;
                  }
                  &:after {
                    content: '';
                    position: absolute;
                    left: calc(100%/2 - 5px);
                    top: 50%;
                    background: #999;
                    width: 40%;
                    height: 1px;
                  }
                }
                .add {
                  padding: 2px 0;
                  width: 30%;
                  height: .6rem;
                  font-size: 14px;
                  text-align: center;
                  position: relative;
                  cursor: pointer;
                  &:before {
                    content: '';
                    position: absolute;
                    left: 0;
                    top: 0;
                    background: #eee;
                    width: 1px;
                    height: 100%;
                  }
                  &:after {
                    content: '+';
                    position: absolute;
                    left: calc(100%/2 - 5px);
                    top: calc(100%/2 - 8px);
                    font-size: 14px;
                    color: #999; // width: 50%;
                    // height: 1px;
                  }
                }
                .num-inp {
                  border: none;
                  outline: none;
                  text-align: center;
                  padding: 0 5px;
                  width: 40%;
                  font-size: 12px;
                }
              }
            }
            .pd-stock {
              text-align: right;
              line-height: 1.5;
              font-size: 12px;
              color: $red;
              span {
                display: inline-block;
                width: 80px;
                text-align: center;
              }
            }
          }
        }
      }
    }
    .empty-info {
      height: 80vh;
    }
  }
  /* 购物车列表 */
  /* 底部计算栏 */

  .section-bar {
    position: fixed;
    border-top: 1px solid #eee;
    bottom: 1.32rem;
    width: 100%;
    background: #fff;
    height: 1.25rem;
    @include flexbox(space-between,
    center,
    row,
    nowrap);
    .left {
      background: #fff;
      height: 100%;
      padding-left: 10px;
      width: 70%;
      @include flexbox(flex-start,
      center,
      row,
      nowrap);
      flex: initial;
      font-size: 14px;
      line-height: 1.25rem;
      i {
        vertical-align: middle;
        font-size: 20px;
        margin-right: 5px;
      }
      strong {
        margin-left: 10px;
        font-weight: normal;
        @include textoverflow(1);
      }
    }
    .right {
      width: 30%;
      height: 100%;
      background: $orange;
      color: #fff;
      @include flexbox(center,
      center,
      row,
      nowrap);
      strong {
        font-size: 17px;
        font-weight: normal;
        span {
          font-size: 14px;
        }
      }
    }
  }
  /* 底部计算栏 */

</style>
